<template>
	<view class="ag_container">
		<!-- 顶部导航 -->
		<uni-nav-bar :fixed="true" backgroundColor="#00a660" color="#fff" shadow height="90rpx">
			<block slot="left">
				<i class="iconfont nav_backIcon" @click="back">&#xe8b8;</i>
				<span style="font-size: 30rpx;">签署信息设置</span>
			</block>
			<block slot="right">
				<view class="nav_btn">
					<button @click="saveContract(false)" class="backBtn" size="mini">保存草稿</button>
					<button @click="nextForm(false)" class="nextSign" size="mini">下一步</button>
				</view>
			</block>
		</uni-nav-bar>
		<!-- 表单填写 -->
		<view class="agree_jn">
			<uni-forms ref="ruleForm" :modelValue="ruleForm" :rules="rules" label-width="200rpx" type="line" label-align="right"> 
				<uni-section class="mb-10 file-top" title="业务分类及签约文件" type="line">
					<template v-slot:right>
						<span style="font-size: 24rpx;color: #999;">
							剩余合同签署量：<span class="themeColor">{{remainingNum}}</span>次
						</span>
					</template>
				</uni-section>
				<uni-forms-item label="合同类型" name="contractTypeId" :required="true" class="paddingAll">
					<uni-data-select v-model="ruleForm.contractTypeId" :localdata="contractArr" :clear="false"
						@change="selectContractType" placeholder="请选择合同类型" />
				</uni-forms-item>
				<uni-forms-item label="业务分类" name="businessTypeId" :required="true" class="paddingAll">
					<uni-data-select v-model="ruleForm.businessTypeId" :localdata="businessArr" :clear="false"
						@change="selectBusinessType" placeholder="请选择业务分类" />
				</uni-forms-item>

				<uni-forms-item ref='wordFile' name="file" class="load-file">
					<view class="" style="margin-left:40rpx ;margin-bottom: 30rpx;">
						<span>签约文件<span style="font-size: 24rpx;">（{{number}}/20）</span></span>
						<view class="file_view">
							<file-upload :contract-id="ruleForm.id" ref="uploadRef"
								:isHavePermissions="contractSignProcessFilePermissions" @getId="getContractID"
								@changeValue="changeValue" @delted="delted" :text="'添加普通合同文件'"></file-upload>
							<button class="upload_btn" @click="openSelectTemplate">
								<i class="iconfont">&#xe67e;</i>选择标准合同模板</button>
						</view>
					</view>
					<view class="" style="margin-left:40rpx ;margin-bottom: 30rpx;">
						<span>签约附件<span style="font-size: 24rpx;">（{{fileNumber}}/10）</span></span>
						<view class="file_view">
							<file-enclosure :contract-id="ruleForm.id" :text="uploadText" />
						</view>
					</view>
				</uni-forms-item>
				<!-- 分割线 -->
				<view class="grayBg"></view>
				<uni-section class="mb-10" title="基本信息" type="line"></uni-section>
				<view class="paddingAll">
				<uni-forms-item label="合同名称" name="name" :required="true">
					<uni-easyinput v-model="ruleForm.name" type="text" placeholder="请输入合同名称" :clearable="false" />
				</uni-forms-item>
				<uni-forms-item label="合同编号" name="contractNumber" :required="true">
					<uni-easyinput v-model="ruleForm.contractNumber" type="text" placeholder="系统自动生成合同编号"
						:clearable="false" disabled />
				</uni-forms-item>
				<uni-forms-item label="签署截止时间" name="signExpiryDate" :required="true">
					<uni-datetime-picker type="datetime" :clear-icon="false" v-model="ruleForm.signExpiryDate" />
				</uni-forms-item>
				<uni-forms-item label="合同有效期限" name="date" :required="false" id="noREq">
					<view class="flex_between">
						<uni-datetime-picker type="date" :clear-icon="false" v-model="ruleForm.contractStartTime" placeholder="开始日期"/>
						<span style="margin: 0 20rpx;">至</span>
						<uni-datetime-picker type="date" :clear-icon="false" v-model="ruleForm.contractEndTime" placeholder="终止日期"/>
					</view>
				</uni-forms-item>
				<uni-forms-item label="发起方私有备注" name="remark">
					<uni-easyinput v-model="ruleForm.remark" type="textarea" placeholder="点击添加备注，仅发起方可见备注信息，最多300字！" />
				</uni-forms-item>
				</view>
			</uni-forms>
			<!-- 分割线 -->
			<view class="grayBg"></view>
			<!-- 签署信息设置 -->
			<uni-section class="mb-10 face-check" :title="'签约方信息（' + setSize +'/10）'" type="line">
				<template v-slot:right>
					<uni-data-checkbox multiple v-model="ruleForm.isFace" :localdata="faceItems" @change="faceCheck" />
					<uni-data-checkbox multiple v-model="ruleForm.isSaveSigner" :localdata="saveItems"
						@change="saveCheck" />
				</template>
			</uni-section>
			<view style="padding: 0 30rpx;">
				<!-- 签署信息 -->
				<view class="sign_item" v-for="item,index in tableData" :key="index">
					<!-- 发起方 -->
					<view v-if="item.isStarter == 1">
						<view class="header_p">
							<view>
								<span class="round_ruleForm" v-if="ruleForm.signSortType == 0">{{index + 1}}</span>
								<span>发起方</span>
								<span v-if="item.signerType == 1">（个人）</span><span v-else>（企业）</span>
							</view>
							<!-- 签署顺序设置 -->
							<span @click="subsequence" v-if="ruleForm.signSortType == 0">顺序签<i
									class="iconfont dianji">&#xe8d4;</i></span>
							<span @click="subsequence" v-if="ruleForm.signSortType == 1">无序签<i
									class="iconfont dianji">&#xe8d4;</i></span>
						</view>
						<view>
							<view v-if="item.signerType == 0">
								<uni-easyinput v-model="item.signCompany" type="text" disabled class="signStart" />
								<uni-easyinput v-model="signerNameText" disabled class="signStart" />
							</view>
							<view v-else>
								<uni-easyinput v-model="signerNameText" disabled class="signStart" />
							</view>
						</view>
						<!-- 发起方企业显示签署流程 -->
						<template v-if="item.signerType == 0 &&item.isStarter == 1">
						  <uni-data-select class="signStart" v-model="item.sealerId" :localdata="options" :clear="false"
						  	placeholder="请选择签章流程" v-if="sealerFlag" @change="changeSignFlow(item)" />
						</template>

						<!-- 签署要求 -->
						<view v-if="item.signerType == 0" class="view_check">
							<span>签署要求</span>
							<uni-data-checkbox multiple v-model="companyCheckbox" :localdata="companyItems" @change="signCompanyAsk" :min="1"
								selectedColor="#00a660" />
						</view>
						<view v-if="item.signerType == 1" class="view_check">
							<span>签署要求</span>
							<uni-data-checkbox multiple v-model="personalCheckbox" :localdata="personalItems" @change="signPersonAsk" :min="1"
								selectedColor="#00a660" />
						</view>
					</view>

					<!-- 接收方 -->
					<view v-else>
						<view class="header_p">
							<view>
								<span class="round_ruleForm" v-if="ruleForm.signSortType == 0">{{index + 1}}</span>
								<span>接收方</span>
								<span v-if="item.signerType == 1">（个人）</span><span v-else>（企业）</span>
							</view>
							<!-- 删除按钮 -->
							<i class="iconfont" @click.stop="remove(index,item.id)">&#xe8c1;</i>
						</view>
						<view v-if="item.isStarter !== 1">
							<view v-if="item.signerType == 0">
								<uni-easyinput v-model="item.signCompany" type="text" class="signStart" @iconClick="iconCompany(index)"
									suffixIcon="forward" placeholder="营业执照上的企业名称" />
								<uni-easyinput v-model="item.signerName" @iconClick="iconCompanyStaff(item,index)"
									class="signStart" suffixIcon="forward" placeholder="经办人或签署人的真实姓名"/>
									<uni-easyinput v-model="item.signerMobile" class="signStart" placeholder="经办人或签署人的实名手机号"/>
							</view>
							<view v-else>
								<uni-easyinput v-model="item.signerName" class="signStart" @iconClick="iconPerson(index)"
									placeholder="签署人真实姓名" suffixIcon="forward" />
								<uni-easyinput v-model="item.signerMobile" class="signStart" 
										placeholder="签署人实名手机号" />
							</view>
						</view>

						<!-- 接收方企业显示签署要求 -->
						<view v-if="item.signerType == 0" class="view_check">
							<span>签署要求</span>
							<uni-data-checkbox multiple v-model="item.receiveCompanyCheckbox" :localdata="companyItems" :min="1"
								selectedColor="#00a660" @change="companySelect(index,$event)"/>
						</view>
						<!-- 接收方个人显示签署要求 -->
						<view v-if="item.signerType == 1" class="view_check">
							<span>签署要求</span>
							<uni-data-checkbox multiple v-model="item.receivePersonalCheckbox" :localdata="personalItems" :min="1"
								selectedColor="#00a660" @change="personalSelect(index,$event)" />
						</view>
					</view>
				</view> 

			</view>

			<!-- 添加 -->
			<view class="add_btn">
				<button @click="addPersonal" size="mini"><i class="iconfont">&#xe647;</i>添加个人</button>
				<button @click="addCompany" size="mini" style="margin-left:40rpx;">
					<i class="iconfont">&#xe647;</i>添加企业</button>
			</view>

			<!-- 分割线 -->
			<view class="grayBg" style="margin: 40rpx 0 0;"></view>
			<!-- 添加抄送人 -->
			<uni-section class="mb-10" title="添加抄送人" type="line"></uni-section>
			<view class="copy">
				<view class="copy_title">
					<p>抄送人<span>（{{this.setSizeCopy}}/10）</span></p>
					<p class="copy_btn">
						<span @click="personalCopy" style="margin-right:40rpx;">抄送个人</span>
						<span @click="companyCopy">抄送企业</span>
					</p>
				</view>
				<view v-if="copytableData.length !== 0 ">
					<view v-for="(item,index) in copytableData" :key="index">
						<!-- 抄送企业 -->
						<view class="copy_vi" v-if="item.senderType == 0">
							<view class="copy_item" @click="copyWrite(item,index)">
								<p class="company">{{item.sendCompany}}</p>
								<p class="personal" style="margin-top:20rpx;">经办人：{{item.sendName}}@{{item.sendMobile}}
								</p>
							</view>
							<i class="iconfont" @click="removeCopy(item.id,index)">&#xe8c1;</i>
						</view>
						<!-- 抄送个人 -->
						<view class="copy_vi" v-else>
							<view class="copy_item" @click="copyWrite(item,index)">
								<p class="personal" style="color: #666;">{{item.sendName}}@{{item.sendMobile}}</p>
							</view>
							<i class="iconfont" @click="removeCopy(item.id,index)">&#xe8c1;</i>
						</view>
					</view>
				</view>
				<view class="empty_text" v-else></view>
			</view>

			<uni-notice-bar text="电子签名不适用下列文书：1、涉及婚姻、收养、继承等人身关系的；2、涉及停止供水、供热、供气等公用事业服务的；3、法律、行政法规规定的不适用电子文书的其他情形。"
				color="#909399" background-color="#f4f4f5" />
		</view>
		<!-- 选择在线模板 -->
		<select-template ref="popupTemplate" @getTemplateId="getTemplateId" :contract-sign-process-template-id="contractSignProcessTemplateId"/>
	</view>
</template>

<script>
	import {getRemainingNum} from "@/api/ec/common/main";
	import { getSignProcess } from "@/api/ec/console/busiConfig/contractSignProcess";
	import {getToken} from "@/utils/auth";
	import config from '@/config'
	import {staffCompanyInfo} from "@/api/ec/work/staff/staff";
	import {genDateUUID,genRandom} from "@/utils/common";
	import {getCompanyInfo} from "@/api/ec/console/busiConfig/systemSet";
	import {getPersonInfo} from "@/api/ec/person/user/systemSet";
	import fileUpload from "@/components/fileUpload/fileUpload"
	import fileEnclosure from "@/components/fileUpload/fileEnclosure"
	import {delContractSignMine,signFlowSet} from "@/api/contractSign";
	import selectTemplate from "./selectTemplate";
	import {listByCompanyId} from "@/api/ec/console/busiConfig/contractType";
	import {listByPermissionsContractTypeId,listBycontractTypeId,
	selectIsHaveBusinessTypePermissions} from "@/api/ec/console/busiConfig/contractBusinessType";
	import {getContract,getContractNumberRule,updateContractInfo,uploadHtml,getContractFlowByContractId,genContractNumber,
	delContractCopy,getContractCopy,getContractFlow,checkContractNumber} from "@/api/ec/work/contract/contract";
	import {addOrReduceDate,parseStrEmpty,parseTime} from "@/utils/ruoyi";
	import {getWordByContractId,uploadAppendixList,uploadContractFileList} from "@/api/ec/work/contract/contractFile";
	import {getCustomerCompany} from "@/api/ec/work/customer/customerCompany";
	import {getCustomerCompanyStaff} from "@/api/ec/work/customer/customerCompanyStaff";
	import {getTemplate} from "@/api/ec/console/busiConfig/template";
	export default {
		components: {fileUpload,fileEnclosure,selectTemplate},
		data() {
			let validateContractType = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请选择合同类型'));
				} else {
					if (parseStrEmpty(this.ruleForm.contractTypeId) == "") {
						callback(new Error('请选择合同类型'));
					}
					callback();
				}
			};
			let validateBusinessType = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请选择业务分类')); 
				} else {
					if (parseStrEmpty(this.ruleForm.businessTypeId) == "") {
						callback(new Error('请选择业务分类'));
					}
					callback();
				}
			};
			return {
				receivePersonalCheckbox:[0,1],
				receiveCompanyCheckbox:[0],
				sealerText:null,// 仅盖印章 盖印章及签字章
				remainingNum:'', //剩余签署量
				dateChecked: true, //日期是否提醒 
				dateEndChecked: true, //日期结束提醒
				nameChecked: true, //合同名称是否自动填写
				numChecked: true, //合同编号是否自动填写      
				fileList: [], //签约文件
				fileListAppendix: [], //附件文件
				isHaveHtml: false,
				number: 0, //合同数量
				fileNumber: 0, //附件数量  
				contractSignProcessTemplateId:null,// 当前选中业务分类中的签署流程模板id
                contractSignProcessFileForm:null,// 本地文件签署流程
				contractSignProcessTemplateForm:null,// 在线模板签署流程
				contractSignProcessFilePermissions: false, // 本地文件 上传 是否有权限
				contractSignProcessTemplatePermissions: false, // 在线模板 上传 是否有权限      
				sealerFlag: true,
				host: config.baseUrl,
				uploadText: '上传附件',
				isCompanySignReceive:0,// 接收方企业授权人签字要求
				isCompanySignHtmlReceive:0,// 接收方企业授权人签字要求 在线模板
				isPersonSign:["0","1"],// 接收方个人签名要求
				personalCheckbox: [0, 1], //发起方个人签署要求
				companyCheckbox: [0], //发起方企业签署要求 
				type: 'bottom',
				startDate: Date.now(),
				// signSetType: 1, //签署流程设置
				isHtml: false, // 是否有html
				setSizeCopy: 0, // 已添加抄送方数
				signMax: 10, //签署方最大个数
				setSize: 1, //签署方个数
				enclosureSize: 0, //附件文档个数
				fileSize: 0, //签署文档个数
				contractArr: [], //合同类型
				businessArr: [], //业务分类
				saveItems: [{
					text: '保存联系人',
					value: 1
				}],
				faceItems: [{
					text: '人脸核身',
					value: 1
				}, ],
				companyItems: [{
						text: '企业印章',
						value: 0,
						disable:true,
					},
					{
						text: '授权人签字章',
						value: 1,
						disable:false,
					}
				],
				personalItems: [{
						text: '标准签字章',
						value: 0
					},
					{
						text: '手写签字章',
						value: 1
					}
				],
				options: [], //签署流程
				copytableData: [],
				tableData: [{
					id: 0,
					sealerId:null,
					signerSort: 1,
					styleId: 0,
					signerName: null, // 签署人姓名
					sealerName:"",// 盖章人姓名
					signerMobile: null, // 签署手机号
					signCompany: "", // 签署公司名 
					signerType: 0, // 0企业 1 个人
					isStarter: 1, // 1发起方 0接收方
					isCompanySign: 0, // 是否法人或授权人签字 默认不签名
					isCompanySeal: 1, // 是否企业印章
					handWriting: 1, //手写签字章
					systemWriting: 1, //标准签字章
					signCreditCode: '', //统一社会信用代码
					personal: '',
					company: '',
					sealInfo:'0,1',// 个人签名 手写0 标准1
				}, ],
				ruleForm: {
					id: 0,
					name: '',
					companyId: 0,
					business: "",
					contract: "",
					signExpiryDate: '', // 签署截止日期
					contractEndTime: "",// 合同终止日期
					contractStartTime: "",// 合同开始日期
					contractNumber: '',
					remark: '',
					fileType: 'html',
					// 启用拒填拒签
					isSignRefuse: 1,
					isSaveSigner: [1], //保存联系人
					isFace: 0, //人脸识别
					signSortType: 0, //1无序签署 //0顺序签署
					contractSignFlowList: [], // 签署方信息
					contractCarbonCopyList: [], // 抄送信息 
				},
				rules: {
					file: [{
						required: true,
						message: "请上传签约文件",
						trigger: "change"
					}],
					name: {
						rules: [{
							required: true,
							errorMessage: "请输入合同名称",
							trigger: "blur"
						}, ]
					},
					signExpiryDate: {
						rules: [{
							required: true,
							errorMessage: "请选择签署截止日期",
							trigger: "change"
						}, ]
					},
					contractNumber: {
						rules: [{
							required: true,
							errorMessage: "请输入合同编号",
							trigger: "blur"
						}, ]
					},
					contractTypeId: {
						rules: [{
							required: true,
							errorMessage: "请选择合同类型",
							trigger: "change"
						}, ]
					},
					businessTypeId: {
						rules: [{
							required: true,
							errorMessage: "请选择业务分类",
							trigger: "change"
						}, ]
					},
				},
			};
		},
		onLoad(option) {
			console.log(option)
			// 添加个人 抄送个人
			this.bindPerson()
			// 添加企业 抄送企业
			this.bindCompany()
			// 签署顺序设置 signSortType 0顺序 1无序 
			uni.$on('signOrder',data => {
				this.tableData = data.tableData
				this.ruleForm.signSortType = data.setVal
			})
			// 从我的模板发起的签约
			if(option.query){
				this.initTemplateData(JSON.parse(option.query))
			}
		},
		created() {
			this.initStarter() //初始 发起方 发起方是当前登录用户 公司或者个人 
			this.getContractType() //查询合同类型  
			// 初始 签署流程定义查询 
			this.getSignFlowSet();
			// 初始 合同信息
			this.initContractData();
			// 默认签署截止日期 7天后
			this.ruleForm.signExpiryDate = parseTime(new Date().setDate(new Date().getDate() + 6), '{y}-{m}-{d} 23:59:59');
			// 初始签署截止日期提醒时间和合同终止日期提醒时间
			this.getSignEndDays();
			// 剩余签署量
			this.getRemainingNum()
		},
		onShow() {
			this.initStarter() //初始 发起方 发起方是当前登录用户 公司或者个人
			
		},
		watch: {
			fileList: {
				handler() {
					this.isHaveHtml = this.fileList.filter(f => f.fileType == 0).length > 0
					// 删除文件后
					setTimeout(() => {
						this.changeBusinessArr();
					}, 500)
					// 若文件为空 则清空 合同文件名
					if (this.fileList.length == 0) {
						this.ruleForm.name = '';
					}
				},
				deep: true
			},
		},
		methods: { 
			/** 从我的模板发起的签约 */
			initTemplateData(option){
				let templateId = option.templateId
				if(!templateId){
					return;
				}
				// 选中合同类型
				this.ruleForm.contractTypeId = option.contractTypeId && Number.parseInt(option.contractTypeId);
				// 根据模板名字创建合同名字
				this.ruleForm.name = option.templateName
				// 创建合同编号
				this.createContractNumber();
				this.rules.file[0].required = false;    
				
				// 异步回显 先加载数据 再渲染到子组件 暂时这样处理
				 setTimeout(()=>{
				    // 若查询到模板id 根据模板id 自动选择标准合同模板文件
				    this.fileList.push({fileType: 0, name: option.templateName, templateId: templateId});
				    // 刷新上传回传列表 
					this.$refs.uploadRef.refreshFileList(this.fileList);
				   },500);       
			},
			/** 快捷选择个人 */
			iconPerson(index){
				uni.navigateTo({
					url:'/pages/sign/select/selectPersonal?index='+index
				})
			},
			/** 快捷选择企业 */
			iconCompany(index){
				uni.navigateTo({
					url:'/pages/sign/select/selectCompany?index='+index
				})
			},
			iconCompanyStaff(item,index){
				let customerCompanyId = item.customerCompanyId?item.customerCompanyId:''
				uni.navigateTo({
					url:'/pages/sign/select/selectCompanyPersonal?index='+index+'&customerCompanyId='+customerCompanyId
				})
			},
			/** 获取剩余签署量 */
			getRemainingNum() {
			  getRemainingNum({staffId:this.$store.getters.staffInfo.id,companyId:this.$store.getters.companyInfo.id}).then((response)=>{
			    this.remainingNum = response.data;
			  });
			},    
			/** 抄送个人 */
			personalCopy(){
				// 最多添加10条 
				if (this.copytableData.length == this.signMax) {
				  uni.showToast({
				    title: "最多填写" + this.setSizeCopy + "个抄送方！",
				    icon: 'warning'
				  })
				  return;
				}else{
				uni.navigateTo({
					url:'/pages/sign/copy/personalCopy'
				})
			  }
			},
			/** 抄送企业 */
			companyCopy(){
				// 最多添加10条 
				if (this.copytableData.length == this.signMax) {
				  uni.showToast({
				    title: "最多填写" + this.setSizeCopy + "个抄送方！",
				    icon: 'warning'
				  })
				  return;
				}else{
				uni.navigateTo({
					url:'/pages/sign/copy/companyCopy'
				})
			  }
			},			
			/** 发起方企业签署要求 */
			signCompanyAsk(e){
				if(e.detail.value.length == 1){
					this.tableData[0].isCompanySign = 0
					this.tableData[0].isCompanySeal = 1
					this.sealerText='仅盖印章';
				}
				if(e.detail.value.length == 2){
					this.tableData[0].isCompanySign = 1
					this.tableData[0].isCompanySeal = 1
					this.sealerText='盖印章及签字章';
				}
				// 控制发起方的签署流程
			    this.options.forEach((item,index)=>{
					this.$set(item,'text','签署人：' + item.sealerName + item.staffPost + this.sealerText)
				})
				
				// 发起方签署人 dom更新
				this.sealerFlag = false;
				this.$nextTick(() => {
				  this.sealerFlag = true;
				})      
				
			},
			/** 发起方个人签署要求 */ 
			signPersonAsk(e){
				if(e.detail.value.length == 1){
					this.$modal.msgError("最少选择一个");
					e.detail.value.forEach(item=>{
						if(item == 0){
							this.tableData[0].sealInfo = 1
						}else if(item == 1){
							this.tableData[0].sealInfo = 0
						}
					})
				}
				if(e.detail.value.length == 2){
				 this.tableData[0].sealInfo = '0,1'
				}
			},
			/** 接收方企业签署要求 */
			companySelect(index,$event){
				let e = $event
				if(e.detail.value.length == 1){
					this.tableData[index].isCompanySign = 0 // 是否法人或授权人签字 默认不签名
					this.tableData[index].isCompanySeal = 1 // 是否企业印章
				}
				if(e.detail.value.length == 2){
				 this.tableData[index].isCompanySign = 1
				 this.tableData[index].isCompanySeal = 1
				}
			},
			/** 接收方个人签署要求 */
			personalSelect(index,$event){
				let e = $event
				if(e.detail.value.length == 1){
					this.$modal.msgError("最少选择一个");
					e.detail.value.forEach(item=>{
						if(item == 0){
							this.tableData[index].sealInfo = 1
						}else if(item == 1){
							this.tableData[index].sealInfo = 0
						}
					})
				}
				if(e.detail.value.length == 2){
				 this.tableData[index].sealInfo = '0,1'
				}
			},
			// 人脸核身
			faceCheck(e) {
				if (e.detail.value == 1) {
					this.ruleForm.isFace = [1]
				}
			},
			// 保存联系人
			saveCheck(e) {
				if (e.detail.value == 1) {
					this.ruleForm.isSaveSigner = [1]
				}
			},
			/** 签署顺序设置 */
			subsequence() {
				uni.navigateTo({
					url: '/pages/sign/orderSet?tableData=' + JSON.stringify(this.tableData)+'&signSortType='+this.ruleForm.signSortType
				})
			},
			/** 抄送跳转详情 */
			copyWrite(itemArr, index) {
				// 企业
				if (itemArr.senderType == 0) {
					uni.navigateTo({
						url: '/pages/sign/copy/companyCopy?ruleForm=' + JSON.stringify(itemArr) + '&company=edit' +
							'&companyCopy=' + 'copy' + '&index=' + index
					})
				} else {
					// 个人
					uni.navigateTo({
						url: '/pages/sign/copy/personalCopy?ruleForm=' + JSON.stringify(itemArr) +
							'&personal=edit' + '&personalCopy=' + 'copy' + '&index=' + index
					})
				}
			},
			// 添加企业 抄送企业
			bindCompany() {
				// 签署
				uni.$on('companyData',data=>{
					// 只选择了添加企业名称
					this.tableData[data.index].signCompany = data.signCompany
					this.tableData[data.index].signerMobile = data.signerMobile
					this.tableData[data.index].signerName = data.signerName
					this.tableData[data.index].customerCompanyId = data.customerCompanyId
				})
				uni.$on('companyStaffData',data=>{
					this.tableData[data.index].signCompany = data.signCompany
					this.tableData[data.index].signerMobile = data.signerMobile
					this.tableData[data.index].signerName = data.signerName
				})
				this.setSize = this.tableData.length //签署
				uni.$on('companyTableData',data=>{
					this.copytableData.push(data.ruleForm)
					this.setSizeCopy = this.copytableData.length //抄送 
				})
			},
			// 添加个人 抄送个人
			bindPerson() {
				let that = this
				uni.$on('staffData',data=>{
					that.tableData[data.index].signerMobile = data.signerMobile
					that.tableData[data.index].signerName = data.signerName
					that.setSize = that.tableData.length //签署
				})
				uni.$on('personalTableData',data=>{
					that.copytableData.push(data.ruleForm)
					that.setSizeCopy = that.copytableData.length //抄送 
					if(data.ruleForm){
						that.checkSetMobileDup(data.ruleForm)
					}
				})
			},
			// 检查抄送人设置的数据是否和接收方数据一样 
			checkSetMobileDup(row) {
			  for (let i = 0; i < this.tableData.length; i++) {
			    let data = this.tableData[i];
			    if (row.sendMobile == data.signerMobile) {
					row.sendMobile = "";
					this.$modal.msgError('抄送人不能和签署方信息重复！');
					// debugger
			        return false;
			    }
			  }
			},   
			/** 删除抄送 */
			removeCopy(id, index) {
				this.copytableData.splice(index, 1);
				this.setSizeCopy -= 1;
			},
			/** 删除签署流程 */
			remove(index, id) {
				this.tableData.splice(index, 1);
				if (!!id) {
					delContractSignMine(id).then(response => {})
				}
				this.setSize -= 1;
			},
			// 加载签署截止日期
			getSignEndDays() {
				if (this.$store.getters.staffInfo.companyId == 0) {
					getPersonInfo().then(response => {
						// 签署截止多少天 提醒时间
						this.ruleForm.signEndDays = response.data.signEndDays
						// 合同终止前多少天 提醒时间
						this.ruleForm.isSignTip = response.data.contractExpireDays
						// 是否签署截止提醒
						this.ruleForm.isSignExpiryTip = response.data.signEndNotice;
						// 是否合同到期提醒
						this.ruleForm.isSignEndTip = response.data.contractExpireNotice;
					});
				} else {
					getCompanyInfo().then(response => {
						this.ruleForm.signEndDays = response.data.signEndDays
						this.ruleForm.isSignTip = response.data.contractExpireDays
						// 是否签署截止提醒
						this.ruleForm.isSignExpiryTip = response.data.signEndNotice;
						// 是否合同到期提醒
						this.ruleForm.isSignEndTip = response.data.contractExpireNotice;
					});
				}
			},
			//切换业务分类 修改签名要求 
      changeBusinessArr() {
        // 未选择分类
        if (!this.ruleForm.businessTypeId) {
          return;
        }
        // 如果不为空 则存在本地文件
        let isLocalFile = this.fileList.find(file => !!file.file);
        // 查询本地文件签署流程要求
        let findBusinessArr = this.businessArr.find(business => business.value == this.ruleForm.businessTypeId);
        this.contractSignProcessTemplateId = findBusinessArr.contractSignProcessTemplateId;
        // 只上传了本地文件
        if (!!isLocalFile && !this.isHaveHtml) {
          // 根据本地文件签署流程id 查询本地文件签署流程信息
          if (findBusinessArr.contractSignProcessFileId == 0) {
            // 如果没有绑定流程id 清空不可点击按钮事件
            this.companyItems[1].disable = false
            return;
          }
          getSignProcess(findBusinessArr.contractSignProcessFileId).then(response => {
            this.processForm = response.data;
			console.log(this.processForm,'2023')
            // 发起方签名要求
            this.tableData[0].isCompanySign = this.processForm.isCompanySign;
			if (this.processForm.isCompanySign == 1) {
			  this.sealerText = '盖印章及签字章';
			  this.companyCheckbox = [0,1]
			  // this.receiveCompanyCheckbox = [0,1]
			  this.$set(this.receiveCompanyCheckbox,[0],0)
			  this.$set(this.receiveCompanyCheckbox,[1],1)
			}
			if (this.processForm.isCompanySign == 0) {
			  this.sealerText = '仅盖印章';
			  this.companyCheckbox = [0]
			  // this.receiveCompanyCheckbox = [0]
			  this.$set(this.receiveCompanyCheckbox,[0],0)
			  this.$set(this.receiveCompanyCheckbox,[1],0)
			}
			this.optionArr(this.sealerText)	
			
            
            // 发起人 接收方 授权人签字按钮不可点击
            this.companyItems[1].disable = true
            // 接收方  企业 授权人签字要求
            this.isCompanySignReceive = this.processForm.isCompanySignReceive;
            // 个人签名要求默认值
            if (this.processForm.isPersonSign != "-1") {
              this.isPersonSign = this.processForm.isPersonSign.split(",");
            }
            this.tableData.filter(e => e.isStarter == 0).forEach(flow => {
              flow.isCompanySign = this.processForm.isCompanySignReceive;
              // 若不等于默认值 -1  则获取配置
              if (this.processForm.isPersonSign != "-1") {
                flow.sealInfo = this.processForm.isPersonSign.split(",");
              }
            });
          })
        }
        // 只上传了在线模板
        if (!isLocalFile && !!this.isHaveHtml) {
          // 根据本地文件签署流程id 查询本地文件签署流程信息
          if (findBusinessArr.contractSignProcessTemplateId == 0) {
            // 如果没有绑定流程id 清空不可点击按钮事件
            this.companyItems[1].disable = true
            // 如果没有绑定流程id 走当前选中模板文件设置的配置
            let filterElement = this.fileList.filter(f => f.fileType == 0)[0];
            // 取第一个选中的模板
            this.getSignSetByContractTemplateId(filterElement.templateId);
            return;
          }
          getSignProcess(findBusinessArr.contractSignProcessTemplateId).then(response => {
            this.processForm = response.data;
            // 根据流程绑定的模板id 查询签署要求
            // 根据流程绑定的模板id 查询签署要求
            this.getSignSetByContractTemplateId(this.processForm.contractTemplateSetId);
          })
        }
        // 上传了本地文件 并上传了在线模板
        if (!!isLocalFile && !!this.isHaveHtml) {
          let sealerPreText = "";
          // 业务分类绑定本地流程
          if (findBusinessArr.contractSignProcessFileId != 0) {
            getSignProcess(findBusinessArr.contractSignProcessFileId).then(response => {
              this.processForm = response.data;
              // 发起方签名要求
              this.tableData[0].isCompanySign = this.processForm.isCompanySign;
              // 接收方 企业 授权人签字模板要求
              this.isCompanySignReceive = this.processForm.isCompanySignReceive;
              if (this.processForm.isCompanySign == 1) {
                sealerPreText = '普通合同：盖印章及签字章&';
              }
              if (this.processForm.isCompanySign == 0) {
                sealerPreText = '普通合同：仅盖印章&';
              }
              this.optionArr(this.sealerText)
            });
          }
          // 业务分类绑定模板id
          if (findBusinessArr.contractSignProcessTemplateId != 0) {
            getSignProcess(findBusinessArr.contractSignProcessTemplateId).then(response => {
              this.processForm = response.data;
              getTemplate(this.processForm.contractTemplateSetId).then(response => {
                let data = response.data;
                // 发起方签名要求
                this.tableData[0].isCompanySignHtml = data.signSet;
                if (data.signSet == 1) {
                  sealerPreText += '标准合同：盖印章及签字章';
                }
                if (data.signSet == 0) {
                  sealerPreText += '标准合同：仅盖印章';
                }
                this.optionArr(this.sealerText)
                // 接收方 企业 授权人签字模板要求
                this.isCompanySignHtmlReceive = data.signSet;
                // 接收方模板要求
                this.tableData.filter(e => e.isStarter == 0).forEach(flow => {
                  flow.isCompanySignHtml = data.signSet;
                });
                this.sealerText = sealerPreText;
              });
            });
          }
        }
        // 盖章人 dom更新
        this.sealerFlag = false;
        this.$nextTick(() => {
          this.sealerFlag = true;
        })
      },
      // 根据合同模板id 查询签署要求
      getSignSetByContractTemplateId(contractTemplateSetId){
        // 根据流程绑定的模板id 查询签署要求
        getTemplate(contractTemplateSetId).then(response => {
          let data = response.data;
          // 发起方签名要求
          this.tableData[0].isCompanySign = data.signSet;
          this.tableData[0].isCompanySignHtml = data.signSet;
          if (data.signSet == 1) {
            this.sealerText = '盖印章及签字章';
            // h5
            this.companyCheckbox = [0,1]
            // this.receiveCompanyCheckbox = [0,1]
			this.$set(this.receiveCompanyCheckbox,[0],0)
			this.$set(this.receiveCompanyCheckbox,[1],1)
          }
          if (data.signSet == 0) {
            this.sealerText = '仅盖印章';
            this.companyCheckbox = [0]
            // this.receiveCompanyCheckbox = [0]
			this.$set(this.receiveCompanyCheckbox,[0],0)
			this.$set(this.receiveCompanyCheckbox,[1],0)
          }
          this.optionArr(this.sealerText)
          // 发起人 接收方 授权人签字按钮不可点击
          this.companyItems[1].disable = true;
          // 接收方  企业 授权人签字要求
          this.isCompanySignReceive = data.signSet;
          this.isCompanySignHtmlReceive = data.signSet;
          // 个人签名要求默认值
          if (!!data.signPerson && data.signPerson != "-1") {
            this.isPersonSign = data.signPerson.split(",");
          }
          this.tableData.filter(e => e.isStarter == 0).forEach(flow => {
            // 接收方企业签名要求
            flow.isCompanySign = data.signSet;
            flow.isCompanySignHtml = data.signSet;
            // 若不等于默认值 -1  则获取配置
            if (!!data.signPerson && data.signPerson != "-1") {
              flow.sealInfo = data.signPerson.split(",");
            }
          });
        });
      },
			/** 控制发起方的签署流程 */
			optionArr(sealerText){
				this.$nextTick(()=>{
					this.options.forEach((item,index)=>{
						this.$set(item,'text','签署人：' + item.sealerName + item.staffPost + sealerText)
					})	
				})
				console.log(this.options)
				this.$forceUpdate()
			},
			/**附件数量 */
			changeNumber(emit) {
				this.fileNumber = emit
			},
			/**合同数量*/
			changeValue(emit) {
				this.number = emit
			},
			delted(emit) {

			},
			// 获取 上传的文件list
			getContractID(fileList) {
				this.fileList = fileList;
				this.createContractNumber();
				// this.ruleForm.id = res.contractId;
				// 合同名称不为空 就不进行重写
				if (this.ruleForm.name.trim() == "") {
					this.ruleForm.name = fileList[0].name;
				}
				this.$refs.wordFile.clearValidate();
				this.rules.file[0].required = false;
			},
			createContractNumber() {
				// 若合同已经存在合同编号 则不进行获取
				if (!this.ruleForm.contractNumber) {
					// 检验唯一
					genContractNumber().then((response) => {
						this.ruleForm.contractNumber = response.msg;
					})
				}
			},
			/** 选择在线模板 */
			openSelectTemplate() {
				// 有权限
				if (this.contractSignProcessTemplatePermissions) {
					this.$refs.popupTemplate.open('bottom')
				} else {
					// 无权限
					this.checkPermissions();
				}
			},
			// 无权限点击按钮
			checkPermissions(){
			  if(!this.contractTypeId || !this.businessTypeId){
			    this.$modal.msgError("请先选择合同类型或业务分类");
			  } else {
			    this.$modal.msgError("您无法在当前业务分类发起签约，请向管理员申请权限");
			  }
			},    
			/* 选择在线模板 **/
			getTemplateId(template) {
				this.$modal.msgSuccess("选择在线模板成功");
				let contractId = this.ruleForm.id
				let onlineFileData = {
					name: template.item.name,
					templateId: template.item.id,
					fileType: 0
				};
				this.fileList.push(onlineFileData);
				// 合同名称不为空 就不进行重写
				if (this.ruleForm.name.trim() == "") {
					this.ruleForm.name = template.item.name;
					this.createContractNumber();
				}
				this.ruleForm.fileType = 'html';
				this.$refs.wordFile.clearValidate();
				this.rules.file[0].required = false;
				// 刷新上传回传列表
				this.$refs.uploadRef.refreshFileList(this.fileList);
				// 0 仅盖印章
				if (template.item.signSet == 0) {
					// 授权人签字按钮不可点击
					this.companyItems[1].disable = true
				}
				// 盖章 + 签名
				if (template.signSet == 1) {
					// 授权人签字可以点击
					// this.companyItems[0].disable = false
				}
				// 根据模板配置 设置模板最大的签署方个数
				this.signMax = template.item.signMax;
				// 检查当前已经添加的签署方个数 如果大于模板个数 就进行删除操作
				if (this.signMax < this.tableData.length) {
					for (let i = 0; i < this.tableData.length; i++) {
						if (this.signMax < this.tableData.length) {
							this.tableData.pop();
						}
					}
				}
			},
			/** 初始 合同信息 */
			initContractData() {
				// 合同id
				if (!this.ruleForm.id) {
					return;
				}
				this.ruleForm.id = parseInt(this.ruleForm.id);
				let contractId = this.ruleForm.id;
				// 查询合同详情
				getContract(contractId).then(response => {
					this.ruleForm = response.data;
					if (this.ruleForm.signExpiryDate == null || this.ruleForm.signExpiryDate.trim() == '') {
						// 默认签署截止日期 3天后
						this.ruleForm.signExpiryDate = parseTime(new Date().setDate(new Date().getDate() + 3),
							'{y}-{m}-{d} 23:59:59');
					}
				});
				// 查询合同附件
				getWordByContractId(contractId).then((response) => {
					response.data.forEach(data => {
						this.$refs.wordFile.clearValidate();
						this.rules.file[0].required = false;
						// 保存草稿后  回显是否有在线模板
						if (data.fileType == 0) {
							this.isHaveHtml = true;
						}
					})
				});
				// 查询合同流程详情
				getContractFlowByContractId(contractId).then(async (response) => {
					if (Object.keys(response.data).length > 0) {
						this.tableData = response.data;
						this.tableData.forEach(data => {
							data.sealInfo = data.sealInfo.split(",");
						})
						//初始 已经添加的数量
						this.setSize = this.tableData.length;
					}
				});
				// 查询合同抄送
				getContractCopy(contractId).then(async (response) => {
					if (Object.keys(response.data).length > 0) {
						this.copytableData = response.data;
						//初始 已经添加抄送的数量
						this.setSizeCopy = this.copytableData.length;
					}
				});
			},
			/** 添加个人 */
			addPersonal() {
				// 最多添加10条
				if (this.tableData.length == this.signMax) {
					this.$modal.msgError('因模板文件限制，最多可添加' + this.signMax + '个签署方');
					return;
				}
				// 计算添加的数
				this.setSize = this.tableData.length+1;
				this.tableData.push({
				  id: 0,
				  amount1: "无序签",
				  name: "",
				  signerSort: this.setSize,
				  amount3: "接收方",
				  signerName: "",// 签署人姓名
				  signerMobile: "",// 签署手机号
				  signCompany: "",// 签署公司名
				  signerType: 1, // 0企业 1 个人
				  isStarter: 0, // 1发起方 2接收方
				  handWriting:1, // 手写签字章
				  systemWriting:1, //标准签字章
				  sealInfo:this.isPersonSign,// 手写和标准
				  sealerIdNumber:'',// 盖章人身份证
				  isBatch:0,// 批量唯一标志
				  receivePersonalCheckbox: this.receivePersonalCheckbox, //接收方个人签署要求
				})      
			},
			/** 添加企业 */
			addCompany() {
				// 最多添加10条
				if (this.tableData.length == this.signMax) {
					this.$modal.msgError("最多填写" + this.signMax + "个签署方！");
					return;
				}
                // 计算添加的企业数
                this.setSize= this.tableData.length+1;
                this.tableData.push({
                  id: 0,
                  signerSort: this.setSize,
                  signerName: "",// 签署人姓名
                  signerMobile: "",// 签署手机号
                  signCompany: "",// 签署公司名
                  signerType: 0, // 0企业 1 个人 
                  isStarter: 0, // 1发起方 2接收方
                  isCompanySign:this.isCompanySignReceive, // 是否法人或授权人签字
                  isCompanySignHtml:this.isCompanySignHtmlReceive, //当本地文件和模板共存 使用当前的字段分别记录 在线模板签署要求
                  isCompanySeal:1, // 是否企业印章
                  sealInfo:["0","1"],// 手写和标准
                  signCreditCode:'', //统一社会信用代码
                  sealerIdNumber:'',// 盖章人身份证
                  isBatch:0,// 批量唯一标志
				  receiveCompanyCheckbox: this.receiveCompanyCheckbox, //接收方企业签署要求
                })
				      
			},
			/** 初始 签署流程定义查询 */
			async getSignFlowSet() {
				let signList = []
				this.sealerText = '仅盖印章';
				// 初始 管理员签章流程
				let adminId = this.$store.getters.staffInfo.adminId;
				if (!!adminId) {
					let flowData = {};
					flowData.sealerId = adminId;
					flowData.disable = false;
					flowData.value = adminId;
					flowData.sealerName = this.$store.getters.staffInfo.adminName;
					flowData.staffPost = '（' + this.$store.getters.staffInfo.adminStaffPost + '）'
					flowData.text = '签署人：' + this.$store.getters.staffInfo.adminName + '（' + this.$store.getters.staffInfo.adminStaffPost + '）' + this.sealerText;
					this.options.push(flowData)
				}
				let legalId = this.$store.getters.staffInfo.legalId;
				if (!!legalId) {
					let flowData = {};
					flowData.sealerId = legalId;
					flowData.disable = false;
					flowData.value = legalId;
					flowData.sealerName = this.$store.getters.staffInfo.legalName;
					await staffCompanyInfo(legalId, this.$store.getters.companyInfo.id).then(response => {
						flowData.staffPost = '（' + response.data.staffPost + '）';
						flowData.text = '签署人：' + this.$store.getters.staffInfo.legalName + '（' + response.data.staffPost + '）' + this.sealerText;
					});
					this.options.push(flowData)
				}

				// 只有企业才进行初始化 
				if (this.$store.getters.staffInfo.companyId != 0) {
					// 只有公司进行设置
					let find = this.options.find(e => e.sealerId == this.$store.getters.staffInfo.id);
					if (!!find) {
						// 初始默认盖章人 
						this.tableData[0].sealerId = find.value;
						this.tableData[0].sealerName = find.sealerName;
					} else {
						// 否则取第一个默认值
						this.tableData[0].sealerId = this.options[0].value;
						this.tableData[0].sealerName = this.options[0].sealerName;
					}
				}
			},
			/** 合同类型 */
			getContractType() {
				// 根据当前登录公司 查询合同类型 
				listByCompanyId().then((response) => {
						let data = response.data;
						var list = []
						for (var i = 0; i < response.data.length; i++) {
							var object = {};
							object.text = response.data[i].name; // 展示text
							object.value = response.data[i].id; // 用id查询
							list.push(object);
						}
						this.contractArr = list
						// 默认选中 超过一项 不进行默认选中
						if (data.length == 1) {
							this.ruleForm.contractTypeId = data[0].id;
						}
						return data[0].id;
					})
					.then((contractId) => {
						// 业务分类
						listBycontractTypeId(contractId).then((response) => {
							var list = []
							for (var i = 0; i < response.data.length; i++) {
								var object = {};
								object.text = response.data[i].name; // 展示text
								object.value = response.data[i].id; // 用id查询
								object.contractSignProcessFileId = response.data[i].contractSignProcessFileId;
								object.contractSignProcessTemplateId = response.data[i]
									.contractSignProcessTemplateId;
								list.push(object);
							}
							this.businessArr = list;
							// 默认选中第一个业务分类 超过一项 不进行默认选中 
							if (response.data.length == 1) {
								this.ruleForm.businessTypeId = response.data[0].id;
								// 校验当前用户是否有权限使用当前业务分类
								this.checkIsHaveBusinessTypePermissions();
								// 业务分类只有一个的时候 主动触发默认盖章人设置
								this.setDefaultSealerPerson();
							}
						});
					});
			},
			/** 初始 发起方 */
			initStarter() {
				// signerType 0企业 1个人
				this.tableData[0].signCompany = this.$store.getters.companyName;
				this.tableData[0].signerMobile = this.$store.getters.staffInfo.mobile;
				// 盖章人身份证
				if (!this.$store.getters.staffInfo.companyId != 0) {
					this.tableData[0].signerType = 1;
					this.tableData[0].signCompany = this.$store.getters.name;
					this.tableData[0].signerName = this.$store.getters.name;
				}
				if (this.tableData[0].signerType == 0) {
					this.signerNameText = "经办人：" + this.$store.getters.name + "@" + this.$store.getters.staffInfo.mobile;
				} else {
					this.signerNameText = this.$store.getters.name + "@" + this.$store.getters.staffInfo.mobile;
				}
			},
			// 设置默认盖章人
			setDefaultSealerPerson() {
				// 只有公司进行设置 
				if (this.$store.getters.staffInfo.companyId == 0) {
					return;
				}
				let find = this.options.find(e => e.sealerId == this.$store.getters.staffInfo.id);
				if (!!find) {
					// 初始默认盖章人 
					this.tableData[0].sealerId = find.value;
					this.tableData[0].sealerName = find.sealerName;
				} else {
					// 否则取第一个默认值
					this.tableData[0].sealerId = this.options[0].value;
					this.tableData[0].sealerName = this.options[0].sealerName;
				}
			},
			checkIsHaveBusinessTypePermissions() {
				// 查询本地文件签署流程要求 
				let findBusinessArr = this.businessArr.find(business => business.value == this.ruleForm.businessTypeId);
				selectIsHaveBusinessTypePermissions(findBusinessArr).then(response => {
					// 本地上传文件 权限
					this.contractSignProcessFilePermissions = response.data.contractSignProcessFilePermissions;
					// 在线模板权限
					this.contractSignProcessTemplatePermissions = response.data
						.contractSignProcessTemplatePermissions;
				});
			},
			/** 选择签章流程  */
			changeSignFlow(row) {
				let obj = this.options.find((item) => { //这里的selectList就是上面遍历的数据源
					return item.sealerId === row.sealerId; //筛选出匹配数据 
				});
				// 修改当前盖章人姓名
				row.sealerName = obj.sealerName;
			},
			/** 更改合同类型  */
			selectContractType(value) {
				this.businessArr = [];
				// 业务分类
				listBycontractTypeId(value).then((response) => {
					// select回显
					var list = []
					for (var i = 0; i < response.data.length; i++) {
						var object = {};
						object.text = response.data[i].name; // 展示text
						object.value = response.data[i].id; // 用id查询
						list.push(object);
					}
					this.businessArr = list;
					this.ruleForm.businessTypeId = null;
				});
			},
			selectBusinessType(e) {
				this.ruleForm.businessTypeId = e;
				// 校验当前用户是否有权限使用当前业务分类
				this.checkIsHaveBusinessTypePermissions();
				
				// 根据业务分类查询绑定的流程
				signFlowSet(this.ruleForm.businessTypeId).then((response)=>{
				  response.data.forEach(item => {
				    let flowData = {};
				    flowData.sealerId = item.sealerId;
				    flowData.sealerName = item.sealerName;
				    flowData.staffPost = '（' + item.staffPost + '）'
					flowData.value = item.sealerId;
					flowData.text = '签署人：' + item.sealerName + '（' + item.staffPost + '）' + this.sealerText;
				    this.options.push(flowData);
				  })
				}).then(()=>{
				  this.options = this.uniqueSealerId(this.options);
				}).then(()=>{
				  // 检查当前经办人和盖章有是否有存在同一个 如果存在 设置默认盖章人就是经办人
				  this.setDefaultSealerPerson();
				});
				// 切换业务分类 查询签署要求
				this.changeBusinessArr();	  
			},
		    // 设置默认盖章人
		    setDefaultSealerPerson() {
		       // 只有公司进行设置
		      if(this.$store.getters.companyId==0){
		        return;
		      }
		      let find = this.options.find(e => e.sealerId == this.$store.getters.staffId);
		      if (!!find) {
		        // 初始默认盖章人
		        this.tableData[0].sealerId = find.sealerId;
		        this.tableData[0].sealerName = find.sealerName;
		      } else {
		        // 否则取第一个默认值
		        this.tableData[0].sealerId = this.options[0].sealerId;
		        this.tableData[0].sealerName = this.options[0].sealerName;
		      }
		    },	
			uniqueSealerId(arr) {
			  const res = new Map();
			  return arr.filter((arr) => !res.has(arr.sealerId) && res.set(arr.sealerId, 1));
			},    
			/** 保留草稿 */
			saveContract() {
        // 不存在签署信息
				this.nextForm(true);
			},
			/**返回 */
			back() {
				uni.showModal({
					title: '系统提示',
					confirmColor: '#00a660',
					confirmText: '保存草稿',
					cancelText: '关闭并删除',
					content: '是否保存草稿',
					success: (res)=> {
						if (res.confirm) {
							this.nextForm(true);
						}
						if (res.cancel) {
              this.$refs.uploadRef.refreshFileList([]);
              this.$tab.reLaunch('/pages/index')
						}
					}
				})
			},
			/**下一步 */
			nextForm(draft) {
				// 校验文件是否上传了 
				if (this.fileList.length == 0) {
					this.$modal.msgError('请上传签约文件！');
					return;
				}
				// 至少选择一个接收方
				if (this.tableData.length == 1) {
					this.$modal.msgError("至少选择一个接收方!");
					return;
				}
				// 校验手机号是否为空
				for (let i = 0; i < this.tableData.length; i++) {
					let item = this.tableData[i];
					if (!item.signerMobile) {
						this.$modal.msgError('签约方手机号不能为空！');
						return;
					}
				}
				// 检查流量包是否足够发起合同 文件数（1个文件消耗1签署量）*签约方个数 
				let total = 0;
				for (let i = 0; i < this.tableData.length; i++) {
					let item = this.tableData[i];
					total += 1;
				}
				let costNumber = this.fileList.length * total;
        // 不是草稿 才进行校验
				if (!draft && costNumber > this.remainingNum) {
					this.$modal.msgError('本次签约需要消耗【' + costNumber + '次】签署量，目前账户仅剩【' + this.remainingNum +
						'次】签署量，请先购买签署量，再发起签约。');
					return;
				}
				this.$refs.ruleForm.validate().then((res) => {
					this.$modal.loading("上传加密中，请稍候");
					let files = [];
					// 排除为在线模板的类型 否则ios有问题
					this.fileList.filter(e => e.fileType != 0).forEach(i => {
						files.push({
							"name": 'file',
						    "uri": i.path
						})
					})
          
					// 上传文件
					uni.uploadFile({
						header: {
							Authorization: "Bearer " + getToken(),
						},
						url: this.host + '/ec/contract/uploadContractFileList', //仅为示例，非真实的接口地址
						files: files,
						name: 'file',
						formData: {
							contractNumber: this.ruleForm.contractNumber,
							contractId: this.ruleForm.id,
							onlineFileList: JSON.stringify(this.fileList.filter(f => f.fileType == 0))
						},
						success: (res) => {
							let response = JSON.parse(res.data)
							if (response.code == 200) {
								// 上传文件返回合同id
								if(!!response.contractId){
								  this.ruleForm.id = response.contractId;
								}              
								// 人脸核身
								if (this.ruleForm.isFace != 0) {
									this.ruleForm.isFace = 1
								}
								// 保存联系人 
								if (this.ruleForm.isSaveSigner != 0) {
									this.ruleForm.isSaveSigner = 1
								} else {
									this.ruleForm.isSaveSigner = 0
								}
								// 设置 文件文件内容待填写
								this.ruleForm.contractSignFlowList = [];
								this.ruleForm.contractCarbonCopyList = [];
								// 签署流程信息
								this.tableData.forEach((data, index) => {
									data.signerSort = index;
									if(data.sealInfo.length > 0){
										data.sealInfo = data.sealInfo.toString();
									}
									this.ruleForm.contractSignFlowList.push(data)
								})
								// 抄送信息
								this.copytableData.forEach(data => {
									this.ruleForm.contractCarbonCopyList.push(data)
								})
								this.ruleForm.companyId = this.$store.getters.staffInfo.companyId;
								this.ruleForm.signExpiryDate = new Date(this.ruleForm.signExpiryDate).setHours(23, 59, 59);
								// 防止没有设置终止日期问题	
								this.ruleForm.contractEndTime = new Date(this.ruleForm.contractEndTime).setHours(23, 59, 59);
								// 防止没有设置开始日期问题
								if(!!this.ruleForm.contractStartTime){
								  this.ruleForm.contractStartTime = new Date(this.ruleForm.contractStartTime).setHours(0,0,0);
								}	              
								// 合同是否有html模板 没有直接进入拖拽控件
								if (this.isHaveHtml) {
									this.ruleForm.status = 2;
								}
								// 没有在线模板 进入拖拽控件
								if (!this.isHaveHtml) {
									this.ruleForm.status = 3;
								}
								// 草稿重写合同状态
								if (draft) {
									this.ruleForm.status = 0;
								}
								// 截止提醒时间
								this.ruleForm.signExpiryDateTip = addOrReduceDate('D', this.ruleForm.signExpiryDate, -this.ruleForm.signEndDays)
								updateContractInfo(this.ruleForm).then(response => {
									this.$modal.closeLoading();
									//清空表单数据
									setTimeout(() =>{
									  // 清空缓存文件
									  this.ruleForm.id = 0;
									  this.ruleForm.contractNumber = null;
									  this.fileList=[];
														this.copytableData = []
									  this.$refs.uploadRef.refreshFileList([]);
									},2000);
                  
									if (!draft && this.isHaveHtml) {
										uni.navigateTo({
											url: '/pages/sign/docfill?id=' + this.ruleForm.id
										})
									}
									// 没有在线模板 进入拖拽控件
									if (!draft && !this.isHaveHtml) {
										uni.navigateTo({
											url: '/pages/sign/upSign?id=' + this.ruleForm.id
										})
									}
									// 草稿
									if (draft) {
										uni.switchTab({
											url: '/pages/index'
										})
									}
								}).catch(error => {

								});
							}
						}
					});
				}).catch(error => {

				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	::v-deep .file-top .uni-section .uni-section-header__content{
		flex: '' !important;
		margin-right: 30rpx !important;
	}
	.nextSign {
	  background: $uni-color-primary;
	  color: #fff;
	  border: solid 1rpx #fff;
	  height: 55rpx;
	  line-height: 55rpx;
	  margin-left: 20rpx;
	}
	::v-deep .uni-navbar__header-btns-left {
	  width: 220rpx !important;
	}
	
	::v-deep .uni-navbar__header-btns-right {
	  width: 420rpx !important;
	}
	::v-deep .load-file .uni-forms-item__label.no-label {
		width: 0 !important;
	}

	::v-deep .uni-section .uni-section-header__slot-right {
		display: flex;
		flex: 1.4;
		align-items: center;
	}

	::v-deep .uni-section .uni-section-header {
		padding: 20rpx 20rpx 12rpx 20rpx;
	}

	::v-deep .uni-input-input {
		color: #666666;
	}

	page {
		background: $uni-bg-color;
	}

	// 选择在线模板
	.upload_btn {
		left: 350rpx;
		position: absolute;
		top: 0;
		color: $uni-color-primary;
		background-color: #fff;
		width: 310rpx;
		font-size: 26rpx;
		height: 80rpx;
		line-height: 80rpx;
		border: 1rpx solid $uni-color-primary;

		&:hover {
			color: #11A983;
			border-color: #b8e5da;
			background-color: #e7f6f3;
		}

		.iconfont {
			font-size: 28rpx;
			margin-right: 5rpx;
		}
	}

	// 公司名称
	.company {
		overflow: hidden;
		white-space: normal;
		text-overflow: ellipsis;
		-webkit-line-clamp: 1; //显示行数
		display: -webkit-box;
		/*作为弹性伸缩盒子模型显示*/
		-webkit-box-orient: vertical;
		/*伸缩盒子的排列方式：从上到下垂直*/
		width: 100%;
	}

	// 暂无数据
	.empty_text {
		margin-top: 15rpx;
		border-top: 1rpx dashed #cccccc;
	}

	.view_check {
		padding: 0 30rpx 30rpx;
		display: flex;
		align-items: center;

		::v-deep .uni-data-checklist {
			margin-left: 40rpx;
		}
	}

	.msg_head {
		display: flex;
		align-items: center;
		marginp: 10rpx 0;
		background-color: #f7f8f8;
		padding: 16rpx;
	}

	// 圆点序号
	.round_ruleForm {
		width: 34rpx;
		height: 34rpx;
		line-height: 34rpx;
		border-radius: 50%;
		text-align: center;
		display: inline-block;
		color: #fff;
		background: $uni-color-primary;
		margin: 0 10rpx;
	}

	.file_view {
		position: relative;
		margin-top: 20rpx;
		display: flex;
		align-items: center;
	}

	.face-check ::v-deep .uni-data-checklist .checklist-group .checklist-box {
		margin-right: 10rpx;
	}

	::v-deep .uni-section .uni-section-header__decoration {
		background-color: $uni-color-primary;
	}

	::v-deep .uni-noticebar__content-text {
		font-size: 22rpx;
	}

	::v-deep .uni-easyinput__content-input {
		font-size: 26rpx
	}

	::v-deep .uni-easyinput {
		font-size: 26rpx
	}

	::v-deep .uni-easyinput__content-textarea {
		font-size: 26rpx
	}

	::v-deep .uni-input-input {
		font-size: 26rpx
	}

	::v-deep .uni-forms-item {
		margin-bottom: 36rpx;
	}

	::v-deep .uni-easyinput__content-textarea {
		height: 80rpx;
		min-height: 80rpx;
	}

	::v-deep .uni-select__selector-item {
		font-size: 26rpx !important;
	}

	::v-deep .uni-select__input-text {
		font-size: 26rpx !important;
	}

	::v-deep .uni-forms-item__label {
		font-size: 26rpx;
		padding: 0 12rpx 0 0;
	}

	::v-deep .uni-date__x-input {
		font-size: 24rpx;
	}

	// 签署要求
	.personal_popup {
		display: flex;
		align-items: center;

		p {
			font-size: 28rpx
		}
	}

	// 抄送
	.copy {
		margin: 0 0 25rpx;
		padding: 0 30rpx;

		.copy_title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 30rpx;

			span {
				font-size: 26rpx;
				color: #3d3d3d;
			}
		}

		.copy_vi {
			display: flex;
			align-items: center;
			justify-content: space-between;
			border: solid 1rpx #dcdcdc;
			border-radius: 6rpx;
			margin-top: 20rpx;
			padding: 20rpx 30rpx;
		}

		.personal {
			color: #999999;
			font-size: 26rpx;
		}

		.copy_btn {
			span {
				color: $uni-color-primary;
			}
		}
	}

	// 签署信息
	.sign_item {
		margin: 0 0 20rpx;
		border: solid 1rpx #dcdcdc;

		.header_p {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx;
			background-color: #f7f8f8;
			// border-right: solid 1rpx #dcdcdc;
		}

		.signStart {
			margin: 30rpx;
			width: 92%;
		}
	}

	// 添加按钮
	.add_btn {
		text-align: center;
		margin-top: 40rpx;

		button {
			border-radius: 10rpx;
			border: solid 1rpx $uni-color-primary;
			background: #fff;
			color: $uni-color-primary;
			width: 260rpx;

			.iconfont {
				color: $uni-color-primary;
				padding: 0 10rpx;
				font-size: 24rpx;
			}
		}

		uni-button:after {
			border-style: none;
		}
	}

	.dianji {
		font-size: 26rpx;
	}

	.paddingAll {
		padding: 0 30rpx 0 10rpx;
	}

	.grayBg {
		background: #f1f1f1;
		content: '';
		height: 20rpx;
		width: 100%;
	}

	.addIcon {
		padding: 0 6rpx;
		font-size: 26rpx;
	}

	.ag_container {
		position: relative;
	}

	.agree_jn {
		padding: 0rpx 0 20rpx 0;
		position: relative;
	}
</style>
